package collection;

import java.util.Collections;
import java.util.Comparator;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class SortJSONArrayTest {
	public static void main(String[] args) {
		JSONArray ja = JSONArray.fromObject("[{ \"os\" : \"Linux\" , \"count\" : 2.0},{ \"os\" : \"Android\" , \"count\" : 18.0}]");
		sort(ja, "count");
		System.out.println(ja);
	}
	
	@SuppressWarnings({ "unchecked" })
	private static void sort(JSONArray ja,final String field){
		Collections.sort(ja, new Comparator<JSONObject>() {
			@Override
			public int compare(JSONObject o1, JSONObject o2) {
				Object f1 = o1.get(field);
				Object f2 = o2.get(field);
				if(f1 instanceof Number && f2 instanceof Number){
					return ((Number)f1).intValue() - ((Number)f2).intValue();
				}else{
					return f1.toString().compareTo(f2.toString());
				}
			}
		});
		
	}
	
}
